// ==UserScript==
// @name         ecs - 日志格式化
// @namespace    http://tako.tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       tako
// @match        *://*/*/logs/*
// @icon         
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  // Your code here...
  var btnParent = document.getElementById("lineNum").parentElement;
  var btn = document.createElement("button");
  btn.setAttribute('class', 'logs-view-button');
  var btnSpan = document.createElement("span");
  btnSpan.innerHTML = "格式化";
  btn.appendChild(btnSpan);
  btnParent.appendChild(btn);

  btn.onclick = () => {
    console.log('测试换行');
    var tArea = document.getElementsByTagName('textarea')[0];
    var p = tArea.parentElement;
    var style = tArea.getAttribute('style');
    var text = tArea.innerHTML;
    var newPreNode = document.createElement('pre');
    newPreNode.setAttribute('style', style);
    newPreNode.style.width = 'auto';
    newPreNode.style.backgroundColor = 'azure';
    p.style.height = '95%';
    var logSpans = highlight(text);
    logSpans.forEach(logSpan => {
      newPreNode.appendChild(logSpan);
      newPreNode.innerHTML += "\n";
    });
    p.appendChild(newPreNode);
    p.removeChild(tArea);
    btnParent.removeChild(btn);
  }

  var originStyle = "color: #000000";
  var infoStyle = "color: #008a00;";
  var warnStyle = "color: #f0a30a;font-weight: bold;";
  var errorStyle = "color: #FF6B68;font-weight: bold;";
  function highlight(text) {
    if(typeof(text)!='string') return "";
    var logs = text.split("\n");
    var logSpans = [];
    logs.forEach(log => {
      var logSpan = format(log);
      logSpans.push(logSpan);
    });
    return logSpans;

  }


  function format(log) {
    var logSpan = document.createElement("span");
    var len = log.length;
    if(len > 100) {
      len = 100;
    }
    var subStr = log.substring(0,len);
    if(subStr.search(/\[WARN\]/)!=-1) {
      logSpan.setAttribute('style', warnStyle);
    } else if(subStr.search(/\[ERROR\]/)!=-1) {
      logSpan.setAttribute('style', errorStyle);
    }
    logSpan.innerHTML = log;
    return logSpan;
  }
})();